import waves from "@/directive/waves"; // Waves directive
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { alertWithCallback, alertMessage, isValidateNull } from "@/utils/utils";
import { mapGetters } from 'vuex';
import { getRoleList, deleteSelectedRole, saveRole, getSystemStructureTree, getSearchUserList, updateRoleUsers, getRolePermissions, updateRolePermissions, getMenuTree } from '../personnel-manage.service';

export default {
  name: 'role-management',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      recordNum: 20, // 分页组件默认的页数, 分页里的select默认10, 20, 50
      totalNum: 0, // 数据总数
      pageNum: 1, // 页数
      queryString: "", // 搜索字段
      dataList: [], // 用户列表
      loading: true, // table loading
      dialogTitle: '', // 新建用户、编辑用户
      editDialogVisible: false,
      roleEditRules: {
        name: [{ required: true, trigger: "change", validator: isValidateNull }],
        code: [{ required: true, trigger: "change", validator: isValidateNull }]
      },
      roleEditForm: {},
      settingRoleDialogVisible: false,
      // 分配人员参数
      userPageNum: 1,
      userTotalNum: 0,
      userQueryString: '',
      userList: [],
      departmentTreeList: [],
      departmentProps: {
        children: "children",
        label: "text"
      },
      routeProps: {
        children: "children",
        label: "name"
      },
      selectedDepartmentId: '',
      selectedRoleId: '',
      checkedType: false,
      checkedList: [], // 选中人员数组
      // 分配人员参数
      // 分配全选参数
      codes: [],
      selectedMenuId: '',
      settingCodesDialogVisible: false,
      menuTreeList: [],
      checkedRows: [] // table checkbox选中数据
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getRoleList();
    this.getDepartmentTreeList();
    this.getMenuTreeList();
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      this.loading = true;
      getRoleList(this.queryString, this.pageNum, this.recordNum).then(res => {
        this.totalNum = res.dataCount;
        this.dataList = res.data;
        this.loading = false;
      });
    },

    // 根据关键字进行搜索
    searchRoles() {
      this.pageNum = 1;
      this.getRoleList();
    },

    // 重置搜索
    resetRoles() {
      this.pageNum = 1;
      this.queryString = '';
      this.getRoleList();
    },

    // 删除职位
    deleteSelectedRole(id) {
      if (this.checkedRows.length == 0) {
        alertMessage('请选择记录', 'warning');
      } else {
        alertWithCallback('此操作将永久删除该角色, 是否继续?', '提示').then(() => {
          const ids = [];
          this.checkedRows.forEach(item => {
            ids.push(item.objectId)
          });
          deleteSelectedRole(ids).then((res) => {
            alertMessage(res.message);
            this.resetRoles();
          }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
        }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
      }
    },

    // 打开新建职位、编辑职位窗体
    openEditRoleDetailDialog(type, selectedData) {
      if (type === 'create') {
        this.dialogTitle = '新建角色';
        // 重置必填项
        this.$nextTick(() => {
          this.roleEditForm = {};
          this.roleEditForm.type = 'create';
          this.$refs.dataForm.resetFields();
        });
      } else {
        this.dialogTitle = '编辑角色';
        this.$nextTick(() => {
          this.roleEditForm = Object.assign({}, selectedData);
          this.roleEditForm.type = 'edit';
          this.$refs.dataForm.resetFields();
        });
      }
      this.editDialogVisible = true;
    },

    // 打开分配人员模态框
    openSettingRoleDialog(row) {
      this.checkedType = false;
      this.settingRoleDialogVisible = true;
      this.userQueryString = '';
      this.selectedRoleId = row.objectId;
      this.selectedDepartmentId = '';
      this.userPageNum = 1;
      this.$refs.departmentTree && this.$refs.departmentTree.setCurrentKey(null);
      this.searchUsers();
    },

    // 创建或者编辑角色信息
    save() {
      // 表单验证
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          saveRole(this.roleEditForm).then(() => {
            this.editDialogVisible = false;
            this.resetRoles();
          }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
        }
      });
    },

    // 获取分配人员左侧菜单树状结果
    getDepartmentTreeList() {
      getSystemStructureTree().then(res => {
        this.departmentTreeList = res.data;
      });
    },

    // 判断分配人员页面时候有操作
    checkChange() {
      if (this.checkedType) {
        alertWithCallback('你还没有保存改动, 是否继续?', '提示').then(() => {
          this.checkedType = false;
          this.searchUsers();
        }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
      } else {
        this.searchUsers();
      }
    },

    // 根据选择的部门来进行搜索分配用户
    searchUsers() {
      getSearchUserList(this.userQueryString, this.userPageNum, this.recordNum, this.selectedRoleId, this.selectedDepartmentId).then(res => {
        this.userList = res.data;
        this.userTotalNum = res.dataCount;
        this.$nextTick(() => {
          this.userList.forEach((data, index) => {
            if (data.checkFlag) {
              this.$refs.userTable.toggleRowSelection(this.userList[index]);
            }
          });
        })
      });
    },

    // 通过关键字进行搜索
    searchUserWithKeyword() {
      this.userPageNum = 1;
      this.checkChange();
    },

    // 通过关键字进行搜索
    resetSearchUserWithKeyword() {
      this.userPageNum = 1;
      this.userQueryString = '';
      this.selectedDepartmentId = '';
      this.$refs.departmentTree && this.$refs.departmentTree.setCurrentKey(null);
      this.checkChange();
    },

    // 通过选中左侧部门进行搜索
    searchUsersWithSelectedDepartment(node) {
      this.userPageNum = 1;
      this.selectedDepartmentId = node.id;
      this.checkChange();
    },

    // 选中取消选用用户
    checkUser() {
      this.checkedType = true;
    },

    // 选中取消用户变化事件
    selectedUserChange(users) {
      this.checkedList = users
    },

    // 保存选中的分配人员
    saveAssignedUsers() {
      this.checkedType = false;
      updateRoleUsers(this.userList, this.checkedList, this.selectedRoleId).then(res => {
        alertMessage(res.message);
        this.resetSearchUserWithKeyword();
        this.resetRoles();
      });
    },

    // 打开分配权限模态框
    openSettingCodeDialog(row) {
      this.settingCodesDialogVisible = true;
      this.checkedType = false;
      this.selectedRoleId = row.objectId;
      this.selectedMenuId = '';
      this.$refs.menuTree && this.$refs.menuTree.setCurrentKey(null);
      this.checkCodesChange();
    },

    // 获取分配权限左侧菜单树状结果
    getMenuTreeList() {
      getMenuTree().then(res => {
        this.menuTreeList = res.data;
      });
    },

    // 根据选择的部门来进行搜索分配用户
    searchCodes() {
      getRolePermissions(this.selectedMenuId, this.selectedRoleId).then(res => {
        this.codes = res.data;
        if (this.codes === null) {
          return
        }
        this.$nextTick(() => {
          this.codes.forEach((data, index) => {
            if (data.checkFlag) {
              this.$refs.menuTable.toggleRowSelection(this.codes[index]);
            }
          });
        })
      });
    },

    // 判断分配权限时候有改动
    checkCodesChange() {
      if (this.checkedType) {
        alertWithCallback('你还没有保存改动, 是否继续?', '提示').then(() => {
          this.checkedType = false;
          this.searchCodes();
        }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
      } else {
        this.searchCodes();
      }
    },

    // 通过选中左侧菜单进行搜索
    searchCodesWithSelectedMenu(node) {
      this.selectedMenuId = node.code;
      this.checkCodesChange();
    },

    // 保存选中的分配权限
    saveAssignedCodes() {
      this.checkedType = false;
      updateRolePermissions(this.codes, this.checkedList, this.selectedRoleId, this.selectedMenuId).then(res => {
        alertMessage(res.message);
        this.searchCodes();
      });
    },

    // 处理checkbox选中行数据
    handleSelectionChange(val) {
      this.checkedRows = val;
    }
  }
}
